import undetected_chromedriver as uc
import os
import tkinter as tk
import tkinter.filedialog
from lxml import etree
import requests
from time import sleep
from selenium.webdriver.common.by import By
from pynput.keyboard import Controller
import tkinter.messagebox
import pandas as pd


class get_image():
    def __init__(self):
        self.con = 1
        self.keys = Controller()
    def get_excel(self):
        try:
            self.number_of_times = int(entry.get())
        except:
            tkinter.messagebox.showinfo(title='错误提示', message='输入的不是纯数字')
        data = pd.read_excel(tkinter.filedialog.askopenfilename(title='选择excel文件:'))
        self.path = tkinter.filedialog.askdirectory(title='选择保存的路径:')
        self.url_list = data['url']
        self.get_chromedriver()
    def get_chromedriver(self):
        window.config(background='yellow')
        self.driver = uc.Chrome(use_subprocess=True)
        con_ci = 1
        for i in self.url_list:
            self.driver.get(i)
            sleep(2)
            self.get_images()
            self.con = 1
            while self.con <= self.number_of_times:
                self.ssss(con_ci)
            con_ci += 1
        text.insert(0, '下载完成')

    def get_images(self):
        window.config(background='yellow')
        url_but = self.driver.find_element(By.XPATH,'//img[@class="serp-item__thumb justifier__thumb"]')
        url_but.click()
        window.config(background='green')

    def ssss(self, con_ci):
        self.driver.find_element(By.XPATH,'//div[@class="MMGallery-Item MMGallery-Item_selected"]/./following-sibling::div[1]').click()
        ertees = etree.HTML(self.driver.page_source)
        img_url = ertees.xpath('//div[@class="MMViewerButtons-OpenImageSizes"]/a/@href')[0]
        # if '.jpg' in img_url:
        #     img_url = img_url.split('.jpg')[0]+'.jpg'
        # elif '.JPG' in img_url:
        #     img_url = img_url.split('.jpg')[0]+'.JPG'
        try:
            img_data = requests.get(img_url)
            if img_data.status_code == 200:
                img_data = img_data.content
                save_path = os.path.join(self.path, str(con_ci), str(self.con) + '.jpg')
                if not os.path.exists(os.path.join(self.path, str(con_ci))):
                    os.makedirs(os.path.join(self.path, str(con_ci)))
                print(save_path)
                with open(save_path, 'wb') as f:
                    f.write(img_data)
                print(img_url)
                print('yes')
                text.insert(0, img_url)
                self.con += 1
        except:
            pass


        

if __name__ == '__main__':
    get_image = get_image()
    # 创建一个主窗口对象
    window = tk.Tk()
    window.title("识图下载器 V2.0")
    window.config(background='red')
    window.geometry('450x600+100+100')
    # 使用按钮控件调用函数
    label = tk.Label(window, text='下方输入每个网页采集几张')
    label.pack()

    entry = tk.Entry()
    entry.pack()
    tk.Button(window, text="点击运行", command=get_image.get_excel).pack()
    text = tk.Listbox(window,width=450,height=200)
    text.pack()
    window.attributes('-topmost',1)
    # 调用mainloop()显示主窗口
    window.mainloop()
